﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using static System.Net.Mime.MediaTypeNames;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace EFCore1
{
  public class MyDbContext : DbContext
  {
    public DbSet<Book> Books { get; set; }
    public DbSet<Person> Persons { get; set; }
    public DbSet<Dog> Dogs { get; set; }
    public DbSet<Cat> Cats { get; set; }
    public DbSet<Bird> Birds { get; set; }

    private readonly ILoggerFactory logger = LoggerFactory.Create(a => a.AddConsole());

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
      base.OnConfiguring(optionsBuilder);
      //  optionsBuilder.UseSqlServer("Server=.;Database=demo1;Trusted_Connection=True;MultipleActiveResultSets=True");

      optionsBuilder.UseSqlServer("Data Source = (localdb)\\ProjectModels; Initial Catalog = EFCoreDemoDB; Integrated Security = True; Connect Timeout = 30; Encrypt = False; Trust Server Certificate = False; Application Intent = ReadWrite; Multi Subnet Failover = False");
      // optionsBuilder.useMySql();
      // optionsBuilder.useNpgsql();//Npgsql 开源免费的优质数据库
      //optionsBuilder.UseSqlServer("Server=.;Database=EFCoreDemoDB;Trusted_Connection=True;MultipleActiveResultSets=true");

      //通过日志显示数据库SQL语句操作
      optionsBuilder.UseLoggerFactory(logger);

      //通过自带的LogTo输出日志
      optionsBuilder.LogTo(msg =>
      {
        if (!msg.Contains("CommandExecuting"))
        {
          return;
        }
        Console.WriteLine(msg);
      });
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      base.OnModelCreating(modelBuilder);
      //从当前程序集加载所有配置类 ：实现了IEntityTypeConfiguration的类
      modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
    }
  }
}
